use std::sync::Arc;
use log::error;
use tokio::sync::mpsc::UnboundedSender;
use crate::connection_manager::event::{ConnectionEvent};
use crate::{RpcEvent, RpcResult};
use crate::error::{CustomerErrorKind, RpcError};

#[derive(Clone)]
pub struct RpcSender {
    sender: Arc<Shared>,
}

struct Shared {
    connection_manager_sender: UnboundedSender<Box<dyn ConnectionEvent>>,
    event_sender: UnboundedSender<Box<dyn RpcEvent>>,
}

impl RpcSender {

    pub fn new(connection_manager_sender: UnboundedSender<Box<dyn ConnectionEvent>>,
               event_sender: UnboundedSender<Box<dyn RpcEvent>>) -> Self {
        Self {
            sender: Arc::new(Shared {
                connection_manager_sender,
                event_sender,
            })
        }
    }

    pub fn send_event(&mut self, event: Box<dyn RpcEvent>) -> RpcResult<()> {
        let send_result = self.sender.event_sender.send(event);
        if let Err(error) = send_result {
            error!("send_event error: {:?}", error);
            return Err(RpcError::CustomerError {error_kid: CustomerErrorKind::SendError, message: "事件发送失败".to_string()});
        }
        Ok(())
    }

    pub fn send_data(&mut self, event: Box<dyn ConnectionEvent>) -> RpcResult<()> {
        let send_result = self.sender.connection_manager_sender.send(event);
        if let Err(error) = send_result {
            error!("send_event error: {:?}", error);
            return Err(RpcError::CustomerError {error_kid: CustomerErrorKind::SendError, message: "数据发送失败".to_string()});
        }
        Ok(())
    }
}